/**
 * HTTP AJAX请求封装
 */
export default class HttpUtil {
  public static baseUrl: string = 'http://localhost:3000'
  public static timeout: number = 3000

  /**
   * HTTP Get请求
   * @param url 
   * @param query 
   * @returns 
   */
  public static get(url: string, query?: object): Promise<unknown> {
    const _url = this.baseUrl + url
    const xhr = new XMLHttpRequest()

    // 参数解析
    let queryStr = ''
    if (query) {
      queryStr = this.queryToString(query)
    }

    const promise = new Promise((resolve, reject) => {
      // init xhr
      xhr.open('GET', _url + queryStr)
      xhr.timeout = this.timeout
      xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
      // xhr.setRequestHeader("Content-Type", "application/JSON");
      // 响应处理
      xhr.onreadystatechange = () => {
        if (xhr.readyState != 4) { return }

        let response: any = xhr.responseText
        // 尝试变为JSON数据
        try {
          response = JSON.parse(xhr.responseText)
        } catch { }

        if (xhr.status >= 200 && xhr.status < 400) {
          resolve(response)
        } else {
          console.error(`post request error\nstatus:${xhr.status}, url:${_url}\nresponse:`, response)
          reject()
        }
      }
      xhr.send()
    })

    return promise
  }

  /**
   * Http Post请求
   * @param url 
   * @param params 
   */
  public static post(url: string, params?: object): Promise<unknown> {
    const _url = this.baseUrl + url
    const xhr = new XMLHttpRequest()

    const promise = new Promise((resolve, reject) => {
      // init xhr
      xhr.open('POST', _url)
      xhr.timeout = this.timeout
      xhr.setRequestHeader("Content-Type", "application/JSON"); // JSON格式
      // 响应处理
      xhr.onreadystatechange = () => {
        if (xhr.readyState != 4) { return }
        let response: any = xhr.responseText
        // 尝试变为JSON数据
        try {
          response = JSON.parse(xhr.responseText)
        } catch { }

        if (xhr.status >= 200 && xhr.status < 400) {
          resolve(response)
        }
        else {
          console.error(`post request error\nstatus:${xhr.status}, url:${_url}\nresponse:`, response)
          reject()
        }
      }
      xhr.send(JSON.stringify(params))
    })

    return promise
  }

  /**
   * 对象参数转成get请求的参数形式
   * @param query 
   * @returns 
   */
  private static queryToString(query: object): string {
    let queryStr = ''
    for (const key in query) {
      if (typeof query[key] !== "object") {
        queryStr += `${key}=${query[key]}`
      }
    }

    if (queryStr == '') {
      return queryStr
    }

    return '?' + queryStr
  }
}